package com.chookss.video;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.home.entity.KnowledgeEntity;
import com.chookss.home.knowledge.adaper.FlowMoreAdapter;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.video.recommend.LongVediosActivity;
import com.chookss.view.FlowLayoutManager;
import com.chookss.view.MaxHeightRecyclerView;
import com.chookss.view.RecycleViewDivider;
import com.chookss.view.listener.ShareDialogListener;
import com.chookss.view.flowLayout.FlowFoldLayout;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.lvgroup.hospital.base.BaseAct;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

//
public class VideoNewCatesActivity extends BaseAct {

    @BindView(R.id.rcvDirectory)
    RecyclerView rcvDirectory;
    @BindView(R.id.tvBottom)
    TextView tvBottom;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBottomSure)
    TextView tvBottomSure;
    @BindView(R.id.llBottom)
    LinearLayout llBottom;
    @BindView(R.id.ivBottomArrow)
    ImageView ivBottomArrow;
    @BindView(R.id.folderFlowLayout)
    MaxHeightRecyclerView folderSelectLayout;
    @BindView(R.id.llBottomPopup)
    LinearLayout llBottomPopup;
    @BindView(R.id.llBottomSure)
    LinearLayout llBottomSure;
    private List<KnowledgeEntity> directoryList = new ArrayList<>();
    private List<KnowledgeEntity> folderSelectList = new ArrayList<>();
    private MyDirectoryAdapter directoryAdapter;
    private FolderSelectAdapter folderSelectAdapter;
    private boolean isOpen = false;//是否展开弹窗默认关闭
    private String videoType = "2";//1小视频2长视频3发布或者修改视频所用4图库过来单独选择的5和6图库过来多选7图文过来单独选择
    private int selectAllNum = 0;//整个视频目录选中文件总数

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_video_cates);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        videoType = getIntent().getStringExtra("videoType");
        if(videoType.equals("4")||videoType.equals("5")||videoType.equals("6")){
            tvTitle.setText("图库");
        }else if(videoType.equals("7")){
            tvTitle.setText("图文");
        }
        MyApp.videoFolderList.clear();
        if(videoType.equals("5")||videoType.equals("6")){
            Bundle bundle = getIntent().getExtras();
            ArrayList videoFolderList = bundle.getParcelableArrayList("videoFolderList");
            MyApp.videoFolderList.addAll((ArrayList<KnowledgeEntity>) videoFolderList.get(0));
        }

        rcvDirectory.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        rcvDirectory.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.HORIZONTAL, Utils.dip2px(this, 0.5f), getResources().getColor(R.color.line_gray)));
        directoryAdapter = new MyDirectoryAdapter(R.layout.item_video_database_directory, this, directoryList);
        rcvDirectory.setAdapter(directoryAdapter);
        folderSelectAdapter = new FolderSelectAdapter(R.layout.item_video_folder_select_list, this, folderSelectList);
        FlowLayoutManager flowLayoutManager = new FlowLayoutManager();
        folderSelectLayout.setLayoutManager(flowLayoutManager);
        folderSelectLayout.setAdapter(folderSelectAdapter);
        getCatalogData();
        llBottomSure.setAlpha((float) 0.6);
    }

    private void getCatalogData() {
        Map<String, String> map = new HashMap<>();
        map.put("parentCode", "");
//        fileFlag 0不包含当前目录文件 1包含
//       totalFlag 0否 1是 为0时，会剔除【我的上传】目录
        String url="";
        if ("3".equals(videoType)) {
            url=Urls.selectAPPCatalogTreeGlobal;
            map.put("fileFlag", "0");
            map.put("totalFlag", "0");
            map.put("catalogType", "1");
        }else  if ("4".equals(videoType)||"5".equals(videoType)||"6".equals(videoType)) {
            //图库
            url=Urls.getAppImageCatalogTree;
            map.put("fileFlag", "1");
            if("5".equals(videoType)||"6".equals(videoType)){
                map.put("totalFlag", "0");
            }else{
                map.put("totalFlag", "1");
            }

        }else  if ("7".equals(videoType)) {
            //图文
            url=Urls.getAppImageTextCatalogTree;
            map.put("fileFlag", "1");
            map.put("totalFlag", "1");

        }else {
            url=Urls.selectAPPCatalogTreeGlobal;
            map.put("fileFlag", "1");
            map.put("totalFlag", "1");
            map.put("catalogType", videoType);
        }
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<List<KnowledgeEntity>>>() {
        }.getType(), null, url, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<KnowledgeEntity>>() {
            @Override
            public void onSuccess(List<KnowledgeEntity> data) {
                if (data != null && data.size() > 0) {
                    directoryList.clear();
                    directoryList.addAll(data);
                    directoryAdapter.notifyDataSetChanged();
                    if(videoType.equals("5")||videoType.equals("6")){
                        changeSelectStatus();
                    }

                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        //比onMoonEvent 慢
        changeSelectStatus();
    }

    private void updateSelect(KnowledgeEntity knowledgeEntity) {
        // 1删除
        if (knowledgeEntity.isSelect()) {
            //普通清除
            for (int i = 0; i < MyApp.videoFolderList.size(); i++) {
                if (MyApp.videoFolderList.get(i).getCode().equals(knowledgeEntity.getCode())) {
                    MyApp.videoFolderList.remove(i);
                    if (i < MyApp.videoFolderList.size()) {
                        i--;
                    }
                }
            }
        } else {
            //半选清除
            for (int i = 0; i < MyApp.videoFolderList.size(); i++) {
                if (MyApp.videoFolderList.get(i).getHierarchyOrgCode().contains(knowledgeEntity.getCode()) || (MyApp.videoFolderList.get(i).getCode().equals(knowledgeEntity.getCode()))) {
                    MyApp.videoFolderList.remove(i);
                    if (i < MyApp.videoFolderList.size()) {
                        i--;
                    }
                }
            }
        }
        changeSelectStatus();
    }

    private void changeSelectStatus() {
        //更新底部弹窗区域数据
        selectAllNum = 0;
        folderSelectList.clear();
        for (int i = 0; i < MyApp.videoFolderList.size(); i++) {
            if (MyApp.videoFolderList.get(i).isSelect()) {
                selectAllNum = selectAllNum + Utils.changeNumber(MyApp.videoFolderList.get(i).getFileNum());
            }
            if (!MyApp.videoFolderList.get(i).isUpperHalfSelect()) {
                //上层是半选的当前层级不显示
                if (MyApp.videoFolderList.get(i).isSelect() || MyApp.videoFolderList.get(i).isHalfSelect()) {
                    folderSelectList.add(MyApp.videoFolderList.get(i));
                }
            }
            KLog.i("------------0" + MyApp.videoFolderList.get(i).getName() + "==" + MyApp.videoFolderList.get(i).isSelect() + "==" + MyApp.videoFolderList.get(i).isHalfSelect() + "==" + MyApp.videoFolderList.get(i).isUpperHalfSelect() + "==" + MyApp.videoFolderList.get(i).getHalfSelectNum());
        }
        folderSelectAdapter.notifyDataSetChanged();
        tvBottom.setText(selectAllNum + "个文件");
        if (videoType.equals("3")||videoType.equals("4")) {
            //发布视频是单选，底部弹窗么有
            llBottomPopup.setVisibility(View.GONE);
            if (MyApp.videoFolderList.size() > 0) {
                tvBottomSure.setText("上传到" + MyApp.videoFolderList.get(0).getName());
                llBottomSure.setAlpha((float) 1.0);
            } else {
                tvBottomSure.setText("确定");
                llBottomSure.setAlpha((float) 0.6);
            }
        } else {
            if (MyApp.videoFolderList.size() > 0) {
                llBottomPopup.setVisibility(View.VISIBLE);
                llBottomSure.setAlpha((float) 1.0);
            } else {
                llBottomPopup.setVisibility(View.GONE);
                llBottomSure.setAlpha((float) 0.6);
            }
        }

    }

    class MyDirectoryAdapter extends BaseQuickAdapter<KnowledgeEntity, BaseViewHolderEx> {
        private Context context;

        public MyDirectoryAdapter(int layoutResId, Context context, @io.reactivex.annotations.Nullable List<KnowledgeEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, KnowledgeEntity item) {
            RelativeLayout rlAll = helper.getView(R.id.rlAll);
            ImageView ivIconType = helper.getView(R.id.ivIconType);
            TextView tvTitle = helper.getView(R.id.tvTitle);
            TextView tvNum = helper.getView(R.id.tvNum);
            View spaceView = helper.getView(R.id.spaceView);
            RelativeLayout rlFlowLayout = helper.getView(R.id.flowLayout);
            tvNum.setText(Utils.changeNumber(item.getFileNum()) + "");
            tvTitle.setText(item.getName());
            ivIconType.setVisibility(View.GONE);
            if (item.getChildList().size() == 0) {
                rlFlowLayout.setVisibility(View.GONE);
                spaceView.setVisibility(View.VISIBLE);
            } else {
                rlFlowLayout.setVisibility(View.VISIBLE);
                spaceView.setVisibility(View.GONE);
                rlFlowLayout.removeAllViews();
                FlowFoldLayout flowFoldLayout=new FlowFoldLayout(context);
                flowFoldLayout.setFold(true);
                flowFoldLayout.setFoldLines(2);
                flowFoldLayout.setEqually(false);
                flowFoldLayout.setVerticalSpacing(Utils.dip2px(context,1));
                flowFoldLayout.setHorizontalSpacing(Utils.dip2px(context,17));
                FlowMoreAdapter adapter = new FlowMoreAdapter();
                adapter.setData(context, item, 1, videoType);
                adapter.setNewData(item.getChildList());
                flowFoldLayout.setAdapter(adapter);
                flowFoldLayout.setMoreClick(new ShareDialogListener() {
                    @Override
                    public void onClick() {
                        toSecond(item);
                    }
                });
                rlFlowLayout.addView(flowFoldLayout);
            }
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    toSecond(item);
                }
            });
        }
    }

    private void toSecond(KnowledgeEntity item) {
        Intent intent = null;
        if (videoType.equals("3")||videoType.equals("4")||videoType.equals("7")) {
            intent = new Intent(this, VideoNewCatesSecondActivity2.class);

        } else {
            intent = new Intent(this, VideoNewCatesSecondActivity.class);
            intent.putExtra("hierarchyOrgCode", item.getCode());
            intent.putExtra("oldDepartmentEntity", item);
        }
        intent.putExtra("parentCode", item.getCode());
        intent.putExtra("parentName", item.getName());
        intent.putExtra("parentFileNum", item.getFileNum());
        intent.putExtra("videoType", videoType);
        intent.putExtra("levelOne", item);
        intent.putExtra("level", 1);
        ArrayList<String> nameList = new ArrayList<>();//组织排列
        nameList.add(item.getName());
        intent.putStringArrayListExtra("nameList", nameList);
        startActivity(intent);
        MyApp.videoFolderMap.clear();
    }

    class FolderSelectAdapter extends BaseQuickAdapter<KnowledgeEntity, BaseViewHolder> {
        private Context context;

        public FolderSelectAdapter(int layoutResId, Context context, @io.reactivex.annotations.Nullable List<KnowledgeEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolder helper, KnowledgeEntity item) {
            LinearLayout llDelete = helper.getView(R.id.llDelete);
            ImageView ivType = helper.getView(R.id.ivType);
            TextView tvTitle = helper.getView(R.id.tvTitle);
            if (item.isSelect()) {
                if (item.getCode().contains("X")) {
                    //文件目录
                    ivType.setBackgroundResource(R.drawable.xwj_list);
                    tvTitle.setText(item.getFolderName() + "的文件(" + item.getFileNum() + ")");
                } else {
                    //文件夹
                    ivType.setBackgroundResource(R.drawable.fxk_qx);
                    tvTitle.setText(item.getName() + "(" + item.getFileNum() + ")");
                }
            } else {
                ivType.setBackgroundResource(R.drawable.fxk_bx);
                tvTitle.setText(item.getName() + "(" + item.getHalfSelectNum() + ")");
            }
            llDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    updateSelect(item);
                }
            });
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();
            if (map.containsKey("nextLayerSelectStatus") && map.containsKey(
                    "nextLayerSelectOrgCode")) {

                boolean nextLayerSelectStatus = Boolean.parseBoolean(map.get("nextLayerSelectStatus"));
                boolean halfSelect = Boolean.parseBoolean(map.get("halfSelect"));
                String nextLayerSelectOrgCode = map.get("nextLayerSelectOrgCode");
                for (int i = 0; i < directoryList.size(); i++) {
                    if (directoryList.get(i).getCode().equals(nextLayerSelectOrgCode)) {
                        directoryList.get(i).setSelect(nextLayerSelectStatus);
                        if (!nextLayerSelectStatus) {
                            if (halfSelect) {
                                directoryList.get(i).setHalfSelect(true);
                                if (map.containsKey("nextLayerSelectHalfNum")) {
                                    directoryList.get(i).setHalfSelectNum(map.get("nextLayerSelectHalfNum"));
                                }
                            } else {
                                directoryList.get(i).setHalfSelect(false);
                            }
                        } else {
                            directoryList.get(i).setHalfSelect(false);
                        }
                    } else {
                        for (int j = 0; j < directoryList.get(i).getChildList().size(); j++) {
                            if (directoryList.get(i).getChildList().get(j).getCode().equals(nextLayerSelectOrgCode)) {
                                directoryList.get(i).getChildList().get(j).setSelect(nextLayerSelectStatus);
                                if (!nextLayerSelectStatus) {
                                    if (halfSelect) {
                                        directoryList.get(i).getChildList().get(j).setHalfSelect(true);
                                    } else {
                                        directoryList.get(i).getChildList().get(j).setHalfSelect(false);
                                    }
                                } else {
                                    directoryList.get(i).getChildList().get(j).setHalfSelect(false);
                                }
                            }
                        }
                    }

                }
            }
        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if ("CloseVideoNewCates".equals(msg)) {
                //刷新最近列表
                finish();
            }
        }
    }

    @OnClick({R.id.title_back, R.id.llBottomSure, R.id.llBottomArrow})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.llBottomSure:
                if (MyApp.videoFolderList.size() == 0) {
                } else {
                    String codes = "", videoNames = "";
                    for (int i = 0; i < MyApp.videoFolderList.size(); i++) {
                        if (MyApp.videoFolderList.get(i).isSelect()) {
                            if (Utils.isNull(codes)) {
                                codes = codes + MyApp.videoFolderList.get(i).getCode();
                                videoNames = videoNames + MyApp.videoFolderList.get(i).getName();
                            } else {
                                codes = codes + "," + MyApp.videoFolderList.get(i).getCode();
                                videoNames = videoNames + "," + MyApp.videoFolderList.get(i).getName();
                            }
                        }
                    }
                    KLog.i(codes);
                    if ("1".equals(videoType)) {
                        //小视频
                        Intent intent = new Intent(this, VideoCatesPlayActivity.class);
                        intent.putExtra("videoCate", codes);
                        intent.putExtra("watermark", "4");
                        intent.putExtra("type", 1);
                        startActivity(intent);
                    } else if ("2".equals(videoType)) {
                        //长视频
                        Intent intent = new Intent(this, LongVediosActivity.class);
                        intent.putExtra("videoCate", codes);
                        startActivity(intent);
                    } else if ("3".equals(videoType)||"4".equals(videoType)||"5".equals(videoType)||"6".equals(videoType)||"7".equals(videoType)) {
                        Map<String, String> map = new HashMap<>();
                        if("5".equals(videoType)||"6".equals(videoType)){
                            map.put("videoCate"+videoType, codes);
                        }else{
                            map.put("videoCate", codes);
                        }

                        map.put("videoNames", videoNames);
                        EventBus.getDefault().post(new MyEvent(map));
                    }
                    EventBus.getDefault().post(new MyEvent("CloseVideoNewCates"));
                }
                break;
            case R.id.llBottomArrow:
                if (isOpen) {
                    isOpen = false;
                    ivBottomArrow.setBackgroundResource(R.drawable.arrow_sq);
                    folderSelectLayout.setVisibility(View.GONE);
                } else {
                    isOpen = true;
                    ivBottomArrow.setBackgroundResource(R.drawable.arrow_zk);
                    folderSelectLayout.setVisibility(View.VISIBLE);
                }
                break;
        }
    }
}
